// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <pollux/core/query_config.h>
#include <pollux/functions/macros.h>

namespace kumo::pollux::functions::sparksql {
    template<typename T>
    struct UuidFunction {
        POLLUX_DEFINE_FUNCTION_TYPES(T);

        static constexpr bool is_deterministic = false;

        // Spark would set the seed with 'random.nextLong()' by 'ResolveRandomSeed'
        // rule.
        void initialize(
            const std::vector<TypePtr> & /*inputTypes*/,
            const core::QueryConfig &config,
            const int64_t *seed) {
            POLLUX_CHECK_NOT_NULL(seed, "seed argument must be constant");
            const int32_t partitionId = config.sparkPartitionId();
            generator_.seed((*seed) + partitionId);
        }

        MELON_ALWAYS_INLINE void call(out_type<Varchar> &result, int64_t /*seed*/) {
            int64_t mostSigBits =
                    (nextLong() & 0xFFFFFFFFFFFF0FFFL) | 0x0000000000004000L;
            int64_t leastSigBits =
                    (nextLong() | 0x8000000000000000L) & 0xBFFFFFFFFFFFFFFFL;
            for (int32_t i = 0; i < 8; ++i) {
                uuid_.data[i] = (mostSigBits >> ((7 - i) * 8)) & 0xFF;
                uuid_.data[i + 8] = (leastSigBits >> ((7 - i) * 8)) & 0xFF;
            }
            constexpr int32_t kUuidStringSize = 36;
            result.resize(kUuidStringSize);
            boost::uuids::to_chars(
                uuid_, result.data(), result.data() + kUuidStringSize);
        }

    private:
        MELON_ALWAYS_INLINE int64_t nextLong() {
            // Follow the org.apache.commons.math3.random.BitsStreamGenerator
            // implementation.
            int64_t high = (int64_t) generator_() << 32;
            int64_t low = (int64_t) generator_() & 4294967295L;
            return high | low;
        }

        std::mt19937 generator_;
        boost::uuids::uuid uuid_;
    };
} // namespace kumo::pollux::functions::sparksql
